package com.zhkj.txg.module.member.ui

import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.ViewTreeObserver
import android.webkit.WebView
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.member.adapter.InterestHorizontalAdapter
import com.zhkj.txg.module.member.entity.InterestEntity
import com.zhkj.txg.module.member.popup.LevelPopupWindow
import com.zhkj.txg.module.member.vm.MemberCardViewModel
import com.zhkj.txg.module.mine.ui.EditUserInfoActivity
import com.zhkj.txg.utils.*
import kotlinx.android.synthetic.main.fragment_member_detail.*

class MemberDetailFragment : ViewModelFragment<MemberCardViewModel>() {

    //    private val welfareAdapter = MemberWelfareAdapter()
    private val horizontalAdapter = InterestHorizontalAdapter()
    private var maxScrollHeight: Int = 0
    private val webView: WebView by lazy { WebView(context) }

    override fun setViewModel(): MemberCardViewModel = createViewModel(true)
    override val layoutResId: Int = R.layout.fragment_member_detail
    override fun initUI() {
        // 我的邀请人
        tvMemberInvite.setOnClickListener {
            startActivity(Intent(requireContext(), MemberInviteActivity::class.java))
        }
        // 订单明细
        tvMemberOrderDetail.setOnClickListener {
            startActivity(Intent(requireContext(), MemberRebateActivity::class.java))
        }
        // 收益明细
        tvMemberEarnings.setOnClickListener {
            startActivity(Intent(requireContext(), MemberIncomeActivity::class.java))
        }
        // 累计收益
        tvMemberBalance.setOnClickListener {
            startActivity(Intent(requireContext(), TotalIncomeActivity::class.java))
        }
        // 奖励中心
        tvMemberAward.setOnClickListener {
            startActivity(Intent(requireContext(), MemberCenterActivity::class.java))
        }
        // 提现
        btnWithDraw.setOnClickListener {
            startActivity(
                Intent(context, MemberWithdrawActivity::class.java)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
            )
        }
        // 等级说明
        tvLevelDesc.setOnClickListener {
            viewModel.memberCardLiveData.value?.response?.data?.levelDesc?.let { list ->
                if (list.isNotEmpty()) buildString {
                    list.forEach { append(it.name).append(':').append(it.explain).append("\n\n") }
                    delete(lastIndex - 1, lastIndex)
                }.let {
                    LevelPopupWindow(requireContext()).setLevelText(it).showPopupWindow()
                }
            }

        }
        // 邀请好友
        tvMemberInviteFriend.setOnClickListener {
            viewModel.memberCardLiveData.value?.response?.data?.shareUrl?.let {
                ShareUtils.shareUrl2Friends(
                    requireContext(),
                    ConfigManager.getShareTitle() ?: "",
                    ConfigManager.getShareContent() ?: "",
                    null, it, true
                )
            }
        }
        // 跳转礼包订单
        with(titleMember) {
            setFragmentStatusBar()
            setRightClickListener(View.OnClickListener {
                startActivity(Intent(requireContext(), MemberOrderListActivity::class.java))
            })
        }
        ivMemberAvatar.setOnClickListener {
            EditUserInfoActivity.start(requireActivity())
        }
        with(rvMemberInterest) {
            layoutManager = LinearLayoutManager(context)
            adapter = horizontalAdapter
        }
        horizontalAdapter.setOnItemChildClickListener { _, view, _ ->
            if (view.id == R.id.tvInterestFooter) viewModel.interestExpand.value =
                viewModel.interestExpand.value?.not() ?: false
        }
        WebViewUtils.initWebView(webView)
        WebViewUtils.addWebView2Container(webView, memberContainer)
        webView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.colorLight))
        // 获取变色的最大滚动距离
        titleMember.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                maxScrollHeight = (ScreenUtil.getScreenWidth(requireContext()) - titleMember.measuredHeight)
                titleMember.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
        // 滚动监听
        scrollView.setOnScrollChangeListener { _: NestedScrollView?, _: Int, scrollY: Int, _: Int, _: Int ->
            if (scrollY <= maxScrollHeight) {
                val alpha = (scrollY.toFloat() / maxScrollHeight * 255).toInt()
                titleMember.setBackgroundColor(Color.argb(alpha, 239, 214, 184))
            } else titleMember.setBackgroundColor(Color.argb(255, 239, 214, 184))
            ivMemberTop.visibility = if (scrollY > 2000) View.VISIBLE else View.GONE
        }
        // 滚动到顶部
        ivMemberTop.setOnClickListener { scrollView.smoothScrollTo(0, 0) }
    }

    override fun initViewModel() {
        viewModel.userInfoChangeSubscribe().observe(viewLifecycleOwner, Observer {
            ImageUtils.loadCircleImage(this, ivMemberAvatar, AccountManager.getAvatar())
            tvMemberName.text = AccountManager.getNickname()
        })
        viewModel.userInfoLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.userInfo?.let { userInfo ->
                ImageUtils.loadCircleImage(this, ivMemberAvatar, userInfo.avatar)
                tvMemberName.text = userInfo.nickname
            }
        })
        // 会员权益是否展开数据观察
        viewModel.interestExpand.observe(this, Observer { expandStatus ->
            viewModel.memberCardLiveData.value?.response?.data?.cardInfo?.let { info ->
                if (expandStatus) horizontalAdapter.setNewData(info.interest)
                else mutableListOf<InterestEntity>().also { list ->
                    list.add(InterestEntity().apply {
                        itemType = 0
                        info.interest.forEach { content.addAll(it.content) }
                    })
                    list.add(InterestEntity().apply {
                        itemType = 1
                        expand = false
                    })
                }.let {
                    horizontalAdapter.setNewData(it)
                }
            }
        })
    }

    override fun initData() {
        // 设置权限Adapter的展开状态
        viewModel.interestExpand.value = false
        viewModel.userCenter()
        viewModel.memberCardLiveData.value?.response?.data?.let { memberCard ->
            tvMemberInviteCode.text = "邀请码:${memberCard.inviteCode}"
            tvMemberBalance.text = SpanUtil.setMoneySymbol(memberCard.earnings.toString())
            ImageUtils.loadImage(this, ivMemberVip, memberCard.levelImage ?: "")
            tvCurrentLevel.text = memberCard.levelName
            tvNextLevel.text = memberCard.nextLevelName
            webView.visibility = if (memberCard.cardInfo?.playDesc.isNullOrEmpty()) View.GONE else View.VISIBLE
            memberCard.cardInfo?.playDesc?.let { WebViewUtils.loadFullScreenHtml(webView, it) }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.memberCardLiveData.value?.response?.data?.progress?.let {
            if (it.toInt() > 0) progress.animate(it.toInt(), 2000)
        }
    }

    override fun onDestroy() {
        if (isDetached)
        WebViewUtils.removeWebView(webView, memberContainer)
        super.onDestroy()
    }
}